<template>
  <div class="order-add-view view-container">

    <header-module
      left-custom
      padding
    >
      <template #left-con>
        <div>
          <span style="font-size: 16px; margin-right: 20px">{{ title }}</span>
        </div>
      </template>

      <template #btn>
        <el-button
          class="main-btn"
          size="small"
          @click="onBack"
        >返回</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="onSave"
        >保存</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="onConfirm"
        >提交审核</el-button>
      </template>

    </header-module>

    <div class="main-content">

      <item-title title="基本信息" />

      <information
        ref="information"
        :datas="datas.order"
        :list="datas.orderDetail"
        @change="baseChange"
      />

      <item-title title="订单产品" />

      <add-product
        ref="product"
        :datas="datas"
        @onDelete="onDelete"
      />

    </div>

  </div>
</template>

<script>
import {useRoute, useRouter} from 'vue-router'
import {defineAsyncComponent, defineComponent, getCurrentInstance, inject, onMounted, reactive, toRefs,} from 'vue'

export default defineComponent({
  name: 'Index',
  components: {
    information:defineAsyncComponent(()=>import('./modules/information.vue')),
    addProduct:defineAsyncComponent(()=>import('./modules/addProduct.vue')),
  },
  setup() {
    const currentInstance = getCurrentInstance()
    const router = useRouter()
    const route = useRoute()
    const api = inject('api')

    var data = reactive({
      datas: {
        order: {
          orderType: '', // 订单类型
          agentId: '', // 代理id
          sellerId:0,
          sellerName:'',
          contractId: '', // 合同id
          distributeId: '', // 配送商id
          terminalId: '', // 终端id
          receiveMoneyType: '', // 保证金
          headName: '', // 负责人名称
          headId: '', // 负责人id
          remark: '', // 备注
          deliveryTime: '', // 发货时间
          isSplit: '1', // 是否分户
          acceptAddress: '', // 收货地址
          acceptUser: '', // 收货人
          acceptTel: '', // 收货人电话
          putOrderTime: '', // 下单时间
          expireDeliveryTime: '',
          agentType: '',
        },
        orderDetail: [],
        deleteDetailIds: [],
      },
      information: null,
      product: null,
      title:'',
    })

    const baseChange = () => {
      data.product.baseChange()
    }

    const onDelete = () => {
      for (let i = 0; i < data.datas.orderDetail.length; i++) {
        if (data.datas.orderDetail[i].id) {
          data.datas.deleteDetailIds.push(data.datas.orderDetail[i].id)
        }
      }
      data.datas.orderDetail = []
    }

    const onBack = () => {
      router.back()
    }

    const getData = (id) => {
      api.order.GET_ORDER_DETAIL(id).then((res) => {
        if (!res.code && res.data) {
          res.data.order.orderDetail.forEach((item) => {
            item.unitOption = item.unitOption ? JSON.parse(item.unitOption) : []
            if (item.putNumber) {
              // if (res.data.order.orderType == 3 || res.data.order.orderType == 4){
              //   const str = Number(item.putNumber * item.tradePrice).toFixed(2)
              //   item.totalAmount = Number(str)
              // }else {
              //   const str = Number(item.putNumber * item.terminalPrice).toFixed(2)
              //   item.totalAmount = Number(str)
              // }
              console.log(item.totalAmount)

              item.number = item.putNumber / item.packNum
            }
            if (item.productName) {
              item.name =
                item.productPopularName +
                '-' +
                item.productName +
                '-' +
                item.packSpecs
            } else {
              item.name = item.productPopularName + '-' + item.packSpecs
            }
          })
          if (!res.data.order.order.contractId){
            res.data.order.order.contractId = ''
          }

          data.datas = res.data.order
          data.datas.deleteDetailIds = []

          setTimeout(()=>{
            if (data.information){
              data.information.getData()
            }
          },500)
        }
      })
    }

    const saveData = () => {
      return new Promise((resolve, reject) => {
        data.information
          .validate()
          .then(() => {
            if (data.product.validate()) {
              data.datas.orderDetail.forEach((item) => {
                item.unitOption = JSON.stringify(item.unitOption)
              })
              data.datas.agentId = Number(data.datas.agentId)
              data.datas.contractId = Number(data.datas.contractId)
              data.datas.distributeId = Number(data.datas.distributeId)
              data.datas.terminalId = Number(data.datas.terminalId)
              if (data.datas.order.id) {
                api.order
                  .ORDER_EDIT(data.datas)
                  .then((res) => {
                    if (!res.code) {
                      data.datas.deleteDetailIds = []
                      resolve('编辑成功')
                    } else {
                      reject(res.msg)
                    }
                  })
                  .catch(() => {
                    reject()
                  })
              } else {
                api.order
                  .ORDER_CREATE(data.datas)
                  .then((res) => {
                    if (!res.code) {
                      data.datas.order.id = res.data.order.id
                      data.datas.deleteDetailIds = []
                      resolve('新建成功')
                    } else {
                      reject(res.msg)
                    }
                  })
                  .catch(() => {
                    reject()
                  })
              }
            } else {
              reject()
            }
          })
          .catch(() => {
            reject()
          })
      })
    }

    const onSave = () => {
      saveData()
        .then((msg) => {
          currentInstance.proxy.customMessage({
            type: 'success',
            message: msg,
          })
          router.back()
        })
        .catch((err) => {
          if (err) {
            currentInstance.proxy.customMessage({ type: 'error', message: err })
          }
        })
    }

    const onConfirm = () => {
      saveData().then((msg) => {
        api.order.ORDER_COMMIT_CHECK(data.datas.order.id).then((res) => {
          if (!res.code) {
            currentInstance.proxy.customMessage({
              type: 'success',
              message: '提交成功',
            })
            router.back()
          } else {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: res.msg,
            })
          }
        })
      })
    }

    onMounted(() => {
      if (route.query.type) {
        data.datas.order.orderType = route.query.type
        if (route.query.type == 1) {
          data.title = '新建直发配送商订单'
        } else if (route.query.type == 2) {
          data.title = '新建直发终端订单'
        } else if (route.query.type == 3) {
          data.title = '新建直发代理订单'
        } else if (route.query.type == 4) {
          data.title = '新建直发商销客户订单'
        }
      }
      if (route.query.id) {
        data.title = '订单编辑'
        getData(route.query.id)
      }
    })

    return {
      ...toRefs(data),

      onDelete,
      onBack,
      onSave,
      onConfirm,
      baseChange,
    }
  },
})
</script>

<style scoped>
</style>
